package lumis.portal.presentation.perspective.admin;

import lumis.portal.PortalException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.presentation.core.LayoutFilePage;
import lumis.portal.serviceinterfaceinstance.ServiceInterfaceInstanceConfig;
import lumis.portal.transaction.ITransaction;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.util.XmlUtil;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.w3c.dom.Element;

/**
 * Behavior that provides the javascript for processing an add of an interface,
 * during the edit of a page.
 *
 * @version $Revision: 13093 $ $Date: 2011-05-28 18:40:18 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
@SuppressWarnings("serial")
public class AddInterfaceBehavior extends DropInterfaceBehavior
{
	@Override
	protected void respond(final AjaxRequestTarget target)
	{
		// read parameters
		LayoutFilePage layoutFilePage = (LayoutFilePage) getComponent();
		final String srcIIParam = layoutFilePage.getRequest().getParameter("srcII");
		
		// create the service interface instance
		final String srcIIId;
		try
		{
			ITransaction transaction = PortalTransactionFactory.createTransaction();
			try
			{
				transaction.begin();
				
				Element dragData = XmlUtil.getDocument(srcIIParam).getDocumentElement();
				ServiceInterfaceInstanceConfig serviceInterfaceInstanceConfig = new ServiceInterfaceInstanceConfig();
				serviceInterfaceInstanceConfig.setPageId(layoutFilePage.getPageWebResource().getPage().getId());
				serviceInterfaceInstanceConfig.setServiceInstanceId(XmlUtil.readNodeString("data/sInstId", dragData));
				serviceInterfaceInstanceConfig.setServiceInterfaceId(XmlUtil.readNodeString("data/iId", dragData));
				serviceInterfaceInstanceConfig.setServiceInterfaceId(XmlUtil.readNodeString("data/iId", dragData));
				srcIIId = ManagerFactory.getServiceInterfaceInstanceManager().add(
						SessionConfig.getCurrentSessionConfig(), serviceInterfaceInstanceConfig, transaction);
				
				transaction.commit();
			}
			finally
			{
				transaction.dispose();
			}
		}
		catch (PortalException e)
		{
			throw new RuntimeException(e);
		}
		
		insertInterfaceInstance(srcIIId, target);
	}
	
	@Override
	protected String getFunctionName()
	{
		return "addInterface";
	}
}